<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { phoneRules } from "../utils/rule";
import { ElMessage, type FormInstance } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Iphone from "@iconify-icons/ep/iphone";
import { sendVerifyCode } from '@/api/common'
import { loginByVerifyCode } from '@/api/user'
import { onBeforeUnmount } from "vue";
import { getTopMenu, initRouter } from "@/router/utils";
import { useRouter } from "vue-router";
const env = import.meta.env
const userStore = useUserStoreHook()
const loading = ref(false);
const ruleForm = reactive({
  phone: env.DEV ? "15682291383" : '',
  verifyCode: ""
});
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text, start, end } = useVerifyCode();

const onLogin = async (formEl?: FormInstance) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate(valid => {
    if (!valid) {
      loading.value = false;
      return
    }
    userStore.loginByVerifyCode({ mobile: ruleForm.phone, code: ruleForm.verifyCode })
      // 模拟登录请求，需根据实际开发进行修改
      .then(() => {
        // 获取后端路由
        return initRouter().then(() => {
          router.push(getTopMenu(true).path)
            .then(() => {
              message("登录成功", { type: "success" });
            });
        });

      }, e => {
        message(e.message, {
          type: 'error'
        });
      }).finally(() => {
        loading.value = false;
      })

  });
};
/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

function handleSend() {
  start(ruleFormRef.value, 'phone')
    .then(() => sendVerifyCode({ mobile: ruleForm.phone }))
    .then((res) => { message(res.message, { type: 'success' }) })
}
</script>

<template>
  <el-form v-if="userStore.currentPage === 1" ref="ruleFormRef" :model="ruleForm" :rules="phoneRules" size="large">
    <Motion>
      <el-form-item prop="phone">
        <el-input v-model="ruleForm.phone" clearable placeholder="手机号码" :prefix-icon="useRenderIcon(Iphone)" />
      </el-form-item>
    </Motion>

    <Motion :delay="100">
      <el-form-item prop="verifyCode">
        <div class="w-full flex justify-between">
          <el-input v-model.trim="ruleForm.verifyCode" @change="end" clearable placeholder="短信验证码"
            :prefix-icon="useRenderIcon('ri:shield-keyhole-line')" />
          <el-button :disabled="isDisabled" class="ml-2" @click="handleSend">
            {{
              text.length > 0
                ? text + "秒后重新获取"
                : "获取验证码"
            }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-button class="w-full mt-4" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)">
        登陆
      </el-button>
    </Motion>

  </el-form>
</template>
